package com.hz.pro.kitchen.config;

import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.concurrent.TimeUnit;

@Slf4j
@Configuration
public class DataSourceConfiguration {

    @Value("${mysql.jdbc.url}")
    private String writeDbUrl;

    @Value("${mysql.jdbc.username}")
    private String writeUsername;

    @Value("${mysql.jdbc.password}")
    private String writePassword;

    /**
     * 平台写库
     * @return
     */
    @Bean(name = "writeDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.config")
    public DataSource writeDataSource() {
        log.info("-------------------- writeDataSource init ---------------------");
        HikariDataSource dataSource = new HikariDataSource();

        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setJdbcUrl(writeDbUrl);
        dataSource.setUsername(writeUsername);
        dataSource.setPassword(writePassword);

        dataSource.setMinimumIdle(60);
        dataSource.setMaximumPoolSize(60);
        dataSource.setMaxLifetime(180000);
        dataSource.setIdleTimeout(TimeUnit.MINUTES.toMillis(10));
        dataSource.setConnectionInitSql("set names utf8mb4");
        dataSource.setConnectionTestQuery("select 'X'");
        dataSource.setValidationTimeout(TimeUnit.SECONDS.toMillis(30));

        dataSource.addDataSourceProperty("cachePrepStmts", "true");
        dataSource.addDataSourceProperty("prepStmtCacheSize", "250");
        dataSource.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
        dataSource.addDataSourceProperty("useServerPrepStmts", "true");
        dataSource.addDataSourceProperty("useLocalSessionState", "true");
        dataSource.addDataSourceProperty("useLocalTransactionState", "true");
        dataSource.addDataSourceProperty("rewriteBatchedStatements", "true");
        dataSource.addDataSourceProperty("cacheResultSetMetadata", "true");
        dataSource.addDataSourceProperty("cacheServerConfiguration", "true");
        dataSource.addDataSourceProperty("elideSetAutoCommits", "true");
        dataSource.addDataSourceProperty("maintainTimeStats", "false");
        return dataSource;
    }
}